<?php
namespace app\jfapp\controller;

use think\App;
use hg\apidoc\annotation as Apidoc;
use app\common\lib\Show;
use think\exception\ValidateException;
use app\jfapp\validate\JfUser as JfUserValidate;
use app\common\model\JfUser as JfUserUserModel;
use think\Exception;
use app\common\lib\Str;
use think\facade\Cache;

/**
 * @Apidoc\Title("绝粪用户登陆")
 * @Apidoc\Group("Login")
 * @Apidoc\Sort("2")
 */

class Login extends JfappBaseController
{
  protected $jf_user_model;
  
  public function __construct(App $app)
  {
      parent::__construct($app);
      $this->jf_user_model = new JfUserUserModel();
  }

  /**
   * @Apidoc\Title("用户登陆")
   * @Apidoc\Desc("用户登陆使用这个接口")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/jfapp/login")
   * @Apidoc\Method("POST")
   * @Apidoc\Tag("登陆")
   * @Apidoc\Param("phone", type="string",require=true, desc="手机号码" )
   * @Apidoc\Param("verifyCode", type="string",require=true, desc="验证码" )
   * @Apidoc\Returned("data", type="object", desc="业务数据")
   */
  public function login()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求'); 
    }
    $qurey_info = $this->request->param();
    try {
      validate(JfUserValidate::class)->scene('login')->check($qurey_info);
    }catch (ValidateException $validateException){
      return Show::error($validateException->getError());
    }
    try {
      // 对比验证码
      $verifyCode = Cache::store('redis')->get($qurey_info['phone']);
      if (empty($verifyCode)) {
        return Show::error('验证码不存在'); 
      }
      if ($verifyCode !== $qurey_info['verifyCode']) {
        return Show::error('验证码不正确'); 
      }
      // 查找用户信息
      $userInfo = $this->jf_user_model->getJfUserByPhone($qurey_info['phone']);
      if (empty($userInfo)){
        // 用户不存在，需要创建新用户
        $newJfUserInfo = [
          'username' => Str::getUsername(),
          'nickname' => Str::getNickname(),
          'phone' => $qurey_info['phone'],
          'avatar' => '/upload/pic/20210529/64c58d26a6c002511d8723a6f3ebbd1f.jpg',
        ];
        $this->jf_user_model->save($newJfUserInfo);
        $userInfo = $this->jf_user_model->getJfUserByPhone($qurey_info['phone']);
      }
      return Show::success($userInfo); 
    } catch (Exception $e) {
      return Show::error($e->getMessage());
    }
  }
  /**
   * @Apidoc\Title("发送验证码")
   * @Apidoc\Desc("发送验证码使用这个接口")
   * @Apidoc\Author("ckmmd")
   * @Apidoc\Url("/jfapp/send_verify_code")
   * @Apidoc\Method("POST")
   * @Apidoc\Tag("验证码")
   * @Apidoc\Param("phone", type="string",require=true, desc="手机号码" )
   * @Apidoc\Returned("data", type="object", desc="业务数据")
   */
  public function sendVerifyCode()
  {
    if (!$this->request->isPost()) {
      return Show::error('错误的请求'); 
    }
    $qurey_info = $this->request->param();
    // 存储登陆信息
    $verifyCode = Str::getVerifyCode();
    Cache::store('redis')->set($qurey_info['phone'],$verifyCode, 60000);
    return Show::success($verifyCode);
  }
}